package com.tsll.aspect;

import com.tsll.annotation.MyLog;
import com.tsll.entity.Staff;
import com.tsll.entity.SysOperLog;
import com.tsll.service.impl.SyOperLogServiceImpl;
import com.tsll.vo.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class LogAspect {
    @Pointcut("@annotation(com.tsll.annotation.MyLog)")
    public void logPointCut() {}
    @Autowired
    private HttpSession session;
    @Autowired
    private SyOperLogServiceImpl service;
    @Autowired
    private HttpServletRequest request;
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint joinPoint)  {
            SysOperLog sysOperLog=new SysOperLog();
            try{
                Object result = joinPoint.proceed();
//            回去调用方法对象
                MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                Method method = signature.getMethod();
//            获取方法的注解对象
                MyLog annotation = method.getAnnotation(MyLog.class);
                String businessName = annotation.businessName();
//            获取操作类型
                sysOperLog.setBusinesstype(businessName);
//            获取方法名
                String name = method.getName();
                sysOperLog.setMethod(name);
//            获取请求方式
                sysOperLog.setRequestmethod(request.getMethod());
//            获取操作人
                Staff staff = (Staff) session.getAttribute("staff");
                sysOperLog.setOpername(staff.getStaffname());
//            请求路径
                sysOperLog.setOperurl(request.getRequestURI());
//            获取请求人的ip
                sysOperLog.setOperip(request.getRemoteAddr());
//            获取请求的参数值
                Object[] args = joinPoint.getArgs();
                String params = Arrays.toString(args);
                sysOperLog.setOperparam(params);
                sysOperLog.setJsonresult(result.toString());
                sysOperLog.setStatus(0);
                sysOperLog.setOpertime(new Date());
                return result;
            }catch (Throwable e ){
                sysOperLog.setStatus(1);
            }finally {
                service.insertOperlog(sysOperLog);
            }
            return new Result(5000,"添加失败",null);
    }
}
